﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MagicArena.framework.physics.util;

namespace MagicArena.framework.physics._2d
{
    public class PhysicsEngine2d : APhysicsEngine
    {
        #region Singleton Code
        public static PhysicsEngine2d Instance
        {
            get
            {
                if (_Instance == null) _Instance = new PhysicsEngine2d();
                return _Instance;
            }
        }
        private static PhysicsEngine2d _Instance;
        private PhysicsEngine2d() : base()
        {

        }
        #endregion

        protected override bool ColliderSupportCheck(ACollider col)
        {
            if (col != null && col is Collider2dRect) return true;
            return false;
        }

        public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
        {
            //TODO Need to add code for onCollisionExit
            bool rtn = false;
            //TODO Physics simulation is VERY inefficient, need to add in two phase collision detection
            ACollider2d a1, a2;
            for (int i = 0, len = Colliders.Count; i < len-1; i++)
            {
                
                a1 = (ACollider2d)Colliders[i];
                for (int j = 1; j < len; j++)
                {
                    a2 = (ACollider2d)Colliders[j];
                    if (a1 is Collider2dRect)
                    {
                        if (a2 is Collider2dRect)
                        {
                            rtn = ShapeIntersector.DoIntersect(((Collider2dRect)a1).Rect, ((Collider2dRect)a2).Rect);
                        }
                        else if (a2 is Collider2dCircle)
                        {
                            rtn = ShapeIntersector.DoIntersect(((Collider2dRect)a1).Rect, ((Collider2dCircle)a2).Circle);
                        }
                    }
                    else if (a1 is Collider2dCircle)
                    {
                        if (a2 is Collider2dRect)
                        {
                            rtn = ShapeIntersector.DoIntersect(((Collider2dRect)a2).Rect, ((Collider2dCircle)a1).Circle);
                        }
                        else if (a2 is Collider2dCircle)
                        {
                            rtn = ShapeIntersector.DoIntersect(((Collider2dCircle)a1).Circle, ((Collider2dCircle)a2).Circle);
                        }
                    }
                    if (rtn)
                    {
                        OnCollision(a1, a2);
                    }
                }
            }
        }

        private void OnCollision(ACollider a1, ACollider a2)
        {
            a1.OnCollision(a2);
            a2.OnCollision(a1);
        }

        
    }
}
